#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
模板使用示例生成脚本
根据现有的DSL模型文件和字段模板，生成使用模板的示例文件
"""

import os
import yaml
import json
from pathlib import Path
from typing import Dict, List, Any, Set

def load_yaml_file(file_path: str) -> Dict[str, Any]:
    """加载YAML文件"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f) or {}
    except Exception as e:
        print(f"Error loading {file_path}: {e}")
        return {}

def load_field_templates() -> Dict[str, Any]:
    """加载字段模板"""
    template_path = "templates/field-templates.yml"
    if not os.path.exists(template_path):
        print(f"Template file not found: {template_path}")
        return {}
    
    return load_yaml_file(template_path)

def analyze_entity_fields(entity_def: Dict[str, Any]) -> Dict[str, Set[str]]:
    """分析实体字段，识别可以使用的模板"""
    field_patterns = {
        'audit_fields': {'createdAt', 'updatedAt', 'createdBy', 'updatedBy'},
        'identity_fields': {'id', 'uuid'},
        'status_fields': {'status', 'state'},
        'soft_delete_fields': {'deletedAt', 'isDeleted'},
        'version_fields': {'version', 'versionNumber'},
        'metadata_fields': {'metadata', 'tags', 'notes'},
        'contact_fields': {'email', 'phone', 'address'},
        'money_fields': {'amount', 'price', 'cost', 'fee'},
        'geo_fields': {'latitude', 'longitude', 'location'},
        'file_fields': {'fileName', 'fileSize', 'filePath', 'fileType'},
        'approval_fields': {'approvedBy', 'approvedAt', 'approvalStatus'},
        'priority_fields': {'priority', 'urgency', 'importance'}
    }
    
    attributes = entity_def.get('attributes', {})
    entity_fields = set(attributes.keys())
    
    applicable_templates = {}
    for template_name, template_fields in field_patterns.items():
        matching_fields = entity_fields.intersection(template_fields)
        if matching_fields:
            applicable_templates[template_name] = matching_fields
    
    return applicable_templates

def create_templated_entity(entity_name: str, entity_def: Dict[str, Any], 
                          applicable_templates: Dict[str, Set[str]]) -> Dict[str, Any]:
    """创建使用模板的实体定义"""
    templated_entity = {
        'extends': list(applicable_templates.keys()),
        'attributes': {}
    }
    
    # 复制描述
    if 'description' in entity_def:
        templated_entity['description'] = entity_def['description']
    
    # 复制identity
    if 'identity' in entity_def:
        templated_entity['identity'] = entity_def['identity']
    
    # 复制非模板字段
    template_fields = set()
    for fields in applicable_templates.values():
        template_fields.update(fields)
    
    attributes = entity_def.get('attributes', {})
    for field_name, field_def in attributes.items():
        if field_name not in template_fields:
            templated_entity['attributes'][field_name] = field_def
    
    # 复制其他部分
    for key in ['associations', 'commands', 'events']:
        if key in entity_def:
            templated_entity[key] = entity_def[key]
    
    return templated_entity

def generate_template_examples():
    """生成模板使用示例"""
    print("🔄 生成模板使用示例...")
    
    # 加载字段模板
    templates = load_field_templates()
    if not templates:
        print("❌ 无法加载字段模板")
        return
    
    # 扫描模型文件
    models_dir = "models"
    if not os.path.exists(models_dir):
        print(f"❌ 模型目录不存在: {models_dir}")
        return
    
    examples = {}
    statistics = {
        'total_entities': 0,
        'templatable_entities': 0,
        'template_usage': {},
        'field_reduction': {'before': 0, 'after': 0}
    }
    
    # 处理每个模型文件
    for file_path in Path(models_dir).glob("*.yml"):
        if file_path.name.endswith('.backup.yml'):
            continue
            
        model_data = load_yaml_file(str(file_path))
        if not model_data or 'entities' not in model_data:
            continue
        
        file_examples = {}
        
        for entity_name, entity_def in model_data['entities'].items():
            statistics['total_entities'] += 1
            
            # 分析可用模板
            applicable_templates = analyze_entity_fields(entity_def)
            
            if applicable_templates:
                statistics['templatable_entities'] += 1
                
                # 统计模板使用
                for template_name in applicable_templates.keys():
                    statistics['template_usage'][template_name] = \
                        statistics['template_usage'].get(template_name, 0) + 1
                
                # 创建模板化实体
                templated_entity = create_templated_entity(
                    entity_name, entity_def, applicable_templates
                )
                
                file_examples[entity_name] = {
                    'original_fields': len(entity_def.get('attributes', {})),
                    'templated_fields': len(templated_entity.get('attributes', {})),
                    'applicable_templates': list(applicable_templates.keys()),
                    'template_fields': {k: list(v) for k, v in applicable_templates.items()},
                    'templated_definition': templated_entity
                }
                
                # 统计字段减少
                statistics['field_reduction']['before'] += len(entity_def.get('attributes', {}))
                statistics['field_reduction']['after'] += len(templated_entity.get('attributes', {}))
        
        if file_examples:
            examples[file_path.stem] = file_examples
    
    # 计算优化效果
    if statistics['field_reduction']['before'] > 0:
        reduction_percentage = (
            (statistics['field_reduction']['before'] - statistics['field_reduction']['after']) 
            / statistics['field_reduction']['before'] * 100
        )
        statistics['field_reduction']['percentage'] = round(reduction_percentage, 2)
    
    # 保存示例
    examples_dir = "examples/templates"
    os.makedirs(examples_dir, exist_ok=True)
    
    # 保存详细示例
    with open(f"{examples_dir}/template-usage-examples.json", 'w', encoding='utf-8') as f:
        json.dump(examples, f, indent=2, ensure_ascii=False)
    
    # 保存统计信息
    with open(f"{examples_dir}/template-optimization-stats.json", 'w', encoding='utf-8') as f:
        json.dump(statistics, f, indent=2, ensure_ascii=False)
    
    # 生成具体的YAML示例文件
    create_yaml_examples(examples, examples_dir)
    
    # 生成报告
    generate_template_report(statistics, examples, examples_dir)
    
    print(f"✅ 模板示例生成完成!")
    print(f"   - 总实体数: {statistics['total_entities']}")
    print(f"   - 可模板化实体: {statistics['templatable_entities']}")
    print(f"   - 字段减少: {statistics['field_reduction'].get('percentage', 0):.1f}%")
    print(f"   - 示例文件: {examples_dir}/")

def create_yaml_examples(examples: Dict[str, Any], output_dir: str):
    """创建YAML示例文件"""
    for file_name, file_examples in examples.items():
        # 创建原始版本和模板版本的对比
        comparison = {
            'description': f'{file_name} 模型的模板化示例',
            'original_entities': {},
            'templated_entities': {}
        }
        
        # 加载原始文件
        original_file = f"models/{file_name}.yml"
        if os.path.exists(original_file):
            original_data = load_yaml_file(original_file)
            if 'entities' in original_data:
                for entity_name in file_examples.keys():
                    if entity_name in original_data['entities']:
                        comparison['original_entities'][entity_name] = \
                            original_data['entities'][entity_name]
        
        # 添加模板化版本
        for entity_name, example_data in file_examples.items():
            comparison['templated_entities'][entity_name] = \
                example_data['templated_definition']
        
        # 保存对比文件
        output_file = f"{output_dir}/{file_name}-template-example.yml"
        with open(output_file, 'w', encoding='utf-8') as f:
            yaml.dump(comparison, f, default_flow_style=False, 
                     allow_unicode=True, indent=2)

def generate_template_report(statistics: Dict[str, Any], examples: Dict[str, Any], 
                           output_dir: str):
    """生成模板优化报告"""
    report_lines = [
        "# 字段模板优化报告",
        "",
        "## 📊 总体统计",
        "",
        f"- **总实体数**: {statistics['total_entities']}",
        f"- **可模板化实体**: {statistics['templatable_entities']}",
        f"- **模板化覆盖率**: {statistics['templatable_entities'] / statistics['total_entities'] * 100:.1f}%",
        f"- **字段减少**: {statistics['field_reduction'].get('percentage', 0):.1f}%",
        f"  - 原始字段总数: {statistics['field_reduction']['before']}",
        f"  - 模板化后字段数: {statistics['field_reduction']['after']}",
        f"  - 减少字段数: {statistics['field_reduction']['before'] - statistics['field_reduction']['after']}",
        "",
        "## 🏷️ 模板使用统计",
        ""
    ]
    
    # 模板使用统计
    for template_name, usage_count in sorted(statistics['template_usage'].items(), 
                                           key=lambda x: x[1], reverse=True):
        report_lines.append(f"- **{template_name}**: {usage_count} 个实体使用")
    
    report_lines.extend([
        "",
        "## 📋 详细示例",
        ""
    ])
    
    # 详细示例
    for file_name, file_examples in examples.items():
        report_lines.append(f"### {file_name}.yml")
        report_lines.append("")
        
        for entity_name, example_data in file_examples.items():
            report_lines.extend([
                f"#### {entity_name} 实体",
                "",
                f"- **原始字段数**: {example_data['original_fields']}",
                f"- **模板化后字段数**: {example_data['templated_fields']}",
                f"- **使用的模板**: {', '.join(example_data['applicable_templates'])}",
                ""
            ])
            
            # 显示模板字段映射
            for template_name, fields in example_data['template_fields'].items():
                report_lines.append(f"  - `{template_name}`: {', '.join(fields)}")
            
            report_lines.append("")
    
    report_lines.extend([
        "## 🎯 优化建议",
        "",
        "1. **立即可应用的模板**:",
        "   - 对于完全匹配的字段（如 `createdAt`, `id`），可以直接使用模板替换",
        "",
        "2. **需要标准化的字段**:",
        "   - 对于有变体的字段（如 `description`），建议先标准化定义",
        "",
        "3. **模板扩展**:",
        "   - 考虑为高频使用的字段组合创建新的模板",
        "",
        "4. **渐进式迁移**:",
        "   - 建议从使用频率最高的模板开始逐步迁移",
        ""
    ])
    
    # 保存报告
    report_file = f"{output_dir}/template-optimization-report.md"
    with open(report_file, 'w', encoding='utf-8') as f:
        f.write('\n'.join(report_lines))

if __name__ == "__main__":
    generate_template_examples()